﻿Namespace Utils
    ''' <summary>
    ''' Class Helper to send email
    ''' 
    ''' How to use it:
    ''' 
    ''' Dim mail As EmailExt = New EmailExt(smtpMailServer)
    ''' mail.From = fromAdr
    ''' mail.To = toAdr
    ''' mail.Cc = "aLeblanc@scief.com" ' ok zou....
    ''' mail.Subject = "ERREUR LEWIS"
    ''' mail.Body = ""
    ''' mail.AddAttachment("C:\temp.txt")
    ''' mail.SendMessage()
    '''
    ''' Optionnal Parameters
    ''' 
    ''' mail.Port Default 25
    ''' mail.User
    ''' mail.Password 
    ''' mail.Domain
    '''
    ''' </summary>
    ''' <remarks></remarks>
    Public Class EmailExt
        '
#Region " Fields "
        Private _server As String
        Private _port As Integer = 25
        Private _user As String
        Private _password As String
        Private _domain As String
        Private _body As String
        Private _subject As String
        Private _from As String
        Private _to As String
        Private _cc As String
        Private _bcc As String
        '
        Private _message As System.Net.Mail.MailMessage
        '
        Private WithEvents smptpClient As System.Net.Mail.SmtpClient
#End Region

#Region " Properties "
        ''' <summary>
        ''' Only one destination
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Property [To]() As String
            Get
                Return _to
            End Get
            Set(ByVal value As String)
                _to = value
            End Set
        End Property
        Public Property Bcc() As String
            Get
                Return _bcc
            End Get
            Set(ByVal value As String)
                _bcc = value
            End Set
        End Property
        Public Property Body() As String
            Get
                Return _body
            End Get
            Set(ByVal value As String)
                _body = value
            End Set
        End Property
        Public Property Cc() As String
            Get
                Return _cc
            End Get
            Set(ByVal value As String)
                _cc = value
            End Set
        End Property
        Public Property Domain() As String
            Get
                Return _domain
            End Get
            Set(ByVal value As String)
                _domain = value
            End Set
        End Property
        Public Property From() As String
            Get
                Return _from
            End Get
            Set(ByVal value As String)
                _from = value
            End Set
        End Property
        Public Property Message() As System.Net.Mail.MailMessage
            Get
                Return _message
            End Get
            Set(ByVal value As System.Net.Mail.MailMessage)
                _message = value
            End Set
        End Property
        Public Property Password() As String
            Get
                Return _password
            End Get
            Set(ByVal value As String)
                _password = value
            End Set
        End Property
        Public Property Port() As Integer
            Get
                Return _port
            End Get
            Set(ByVal value As Integer)
                _port = value
            End Set
        End Property
        Public Property Server() As String
            Get
                Return _server
            End Get
            Set(ByVal value As String)
                _server = value
            End Set
        End Property
        Public Property Subject() As String
            Get
                Return _subject
            End Get
            Set(ByVal value As String)
                _subject = value
            End Set
        End Property
        Public Property User() As String
            Get
                Return _user
            End Get
            Set(ByVal value As String)
                _user = value
            End Set
        End Property
#End Region

#Region " Methode "
        Public Sub New()
            Me.Message = New System.Net.Mail.MailMessage()
        End Sub
        ''' <summary>
        ''' Contructor with connection information
        ''' </summary>
        ''' <param name="server"></param>
        ''' <param name="user"></param>
        ''' <param name="password"></param>
        ''' <param name="domain"></param>
        ''' <remarks></remarks>
        Public Sub New(ByVal server As String, Optional ByVal user As String = "", Optional ByVal password As String = "", Optional ByVal domain As String = "")
            Me.New()
            Me.Server = server
            Me.User = user
            Me.Password = password
            Me.Domain = domain
        End Sub
        ''' <summary>
        ''' Validate the filename and add it to the attachement collection of the messages
        ''' </summary>
        ''' <param name="filename"></param>
        ''' <remarks></remarks>
        Public Sub AddAttachment(ByVal filename As String)
            If System.IO.File.Exists(filename) Then
                Me.Message.Attachments.Add(New System.Net.Mail.Attachment(filename, GetMIMEType(filename)))
            Else
                Throw New FileNotFoundException(String.Format("File not found {0}", filename))
            End If
        End Sub
        ''' <summary>
        ''' Go in the regestry to get the myme type of the file
        ''' </summary>
        ''' <param name="filepath"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Shared Function GetMIMEType(ByVal filepath As String) As String
            Dim regPerm As Security.Permissions.RegistryPermission = New Security.Permissions.RegistryPermission(Security.Permissions.RegistryPermissionAccess.Read, "\HKEY_CLASSES_ROOT")
            Dim classesRoot As Microsoft.Win32.RegistryKey = Microsoft.Win32.Registry.ClassesRoot
            Dim fi As System.IO.FileInfo = New System.IO.FileInfo(filepath)
            Dim dotExt As String = fi.Extension.ToLower
            Dim typeKey As Microsoft.Win32.RegistryKey = classesRoot.OpenSubKey("MIME\Database\Content Type")
            Dim Keyname As String = ""
            For Each key As String In typeKey.GetSubKeyNames
                Dim curKey As Microsoft.Win32.RegistryKey = classesRoot.OpenSubKey("MIME\Database\Content Type\" + key)
                If CType(curKey.GetValue("Extension"), String) = dotExt Then
                    Keyname = Keyname
                End If
            Next
            Return Keyname
        End Function
        ''' <summary>
        ''' Construct the message information and send it.
        ''' </summary>
        ''' <remarks></remarks>
        Public Sub SendMessage()
            Try
                smptpClient = New System.Net.Mail.SmtpClient(Me.Server, Me.Port)
                smptpClient.DeliveryMethod = Net.Mail.SmtpDeliveryMethod.Network
                'smptpClient.Credentials....Maybe this way .......BD 2011-12-19
                '
                If Not String.IsNullOrEmpty(Me.User) AndAlso Not String.IsNullOrEmpty(Me.Password) Then
                    Dim credential As System.Net.NetworkCredential = New System.Net.NetworkCredential(Me.User, Me.Password)
                    If Not String.IsNullOrEmpty(Me.Domain) Then
                        credential.Domain = Me.Domain
                    End If
                    smptpClient.Credentials = credential
                End If
                '
                Me.Message.From = New System.Net.Mail.MailAddress(Me.From)
                Me.Message.To.Add(Me.To)
                'Me.Message.ReplyTo = New System.Net.Mail.MailAddress(Me.From)
                Me.Message.Subject = Me.Subject
                Me.Message.Body = Me.Body
                '
                If Not String.IsNullOrEmpty(Me.Cc()) Then
                    Me.Message.CC.Add(Me.Cc())
                End If
                If Not String.IsNullOrEmpty(Me.Bcc()) Then
                    Me.Message.Bcc.Add(Me.Bcc)
                End If
                'Fonctionne pas tjrs.... Ex: relais.videoron.ca
                'smptpClient.SendAsync(Me.Message, Me)
                smptpClient.Send(Me.Message)
            Catch ex As Exception
                Throw New Exception(String.Format("Error in Sendmessage with subject {0}, using server {1}{2}{2}{2}{3}", Me.Subject, Me.Server, vbCrLf, ex.Message), ex)
            End Try
        End Sub
        ''' <summary>
        ''' This sub is call by the SendAsync when finish.
        ''' </summary>
        ''' <param name="sender"></param>
        ''' <param name="e"></param>
        ''' <remarks></remarks>
        Private Sub smptpClient_SendCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.AsyncCompletedEventArgs) Handles smptpClient.SendCompleted
            Dim exMail As EmailExt = CType(e.UserState, EmailExt)
            If e.Cancelled Then
                Throw New OperationCanceledException(String.Format("Operation cancelled. Message with subject {0}", exMail.Message.Subject))
            End If
            '
            If e.Error IsNot Nothing Then
                Throw New Exception(String.Format("An error occur {0}. Message With Subject {1}", e.Error.Message, exMail.Message.Subject), e.Error)
            End If
        End Sub
#End Region
    End Class
End Namespace
